package com.myjar.excel.v2;

import com.myjar.excel.ExcelType;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class POiWorkbook implements _Workbook {

    private Workbook workbook;

    public POiWorkbook(InputStream inputStream) {
        existsWorkbook(inputStream);
    }

    public POiWorkbook(ExcelType type) {
        emptyWorkbook(type);
    }

    public POiWorkbook() {
    }

    @Override
    public void emptyWorkbook(ExcelType excelType) {
        workbook = excelType.workbook();
    }

    @Override
    public void existsWorkbook(InputStream inputStream) {
        try {
            workbook = WorkbookFactory.create(inputStream);
        } catch (IOException | InvalidFormatException e) {
            e.printStackTrace();
        }
    }

    @Override
    public _Sheet getSheet(int index) {
        return new POiSheet(workbook.getSheetAt(index));
    }

    @Override
    public _Sheet createSheet(String name) {
        return new POiSheet(workbook.createSheet(name));
    }

    @Override
    public int sheetSize() {
        return isNull() ? 0 : workbook.getNumberOfSheets();
    }

    @Override
    public void writeTo(OutputStream outputStream) {
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() throws IOException {
        workbook.close();
    }

    @Override
    public boolean isNull() {
        return workbook == null;
    }
}
